import * as React from "react";
import {
  Image,
  StyleSheet,
  Text,
  ToastAndroid,
  TouchableNativeFeedback,
  View,
} from "react-native";
import Carousel from "react-native-snap-carousel";
import { Card } from "react-native-shadow-cards";
import NetInfo from "@react-native-community/netinfo";
//引入工具类
import app from "../utils/util";
import StorageUtil from "../utils/StorageUtil";
import storage from "../utils/StorageUtil";

let banner = [];

function banner_data(callback) {
  //获取随机三个轮播图数据
  for (let i = 0; i < 5; i++) {
    let num = parseInt(Math.random() * app.number, 10) + 1;
    app.QQ("detail?id=" + num + "&appkey=").then(res => {
      if (res.code == "10000") {
        banner.push(res.result.result);
        if (banner.length == 3) {
          StorageUtil.set("banner", banner);
          //回调过去
          callback(banner);
        }
      } else {
        ToastAndroid.show("数据请求错误", 1000);
      }
    });
  }
}

export default class Banner extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      entries: [
        // {
        //   title: "白菜",
        //   imgurl: "http://api.jisuapi.com/recipe/upload/20160719/115137_60657.jpg",
        //   content: "醋溜白菜，是北方人经常吃的一道菜，尤其是在多年前的冬天。那时，没有大棚菜，冬天，家家每天佐餐的基本上都是冬储大白菜，聪明的家庭主妇总是想方设法将这单调的菜变成多种菜式，于是，醋溜白菜被频繁的端上餐桌。美食不分贵贱，用最平凡的原料、最简单的调料和最普通的手法做出美味的菜肴来才是美食的真谛。这次，我做的醋溜白菜，近似鲁菜的做法，使个这道菜酸甜浓郁、开胃下饭、老少咸宜。",
        //   peoplenum: "1-2人",
        // },
        // {
        //   title: "葱煎蛋",
        //   imgurl: "https://pic.ecook.cn/web/6894443.jpg",
        //   content: "鸡蛋含有丰富的蛋白质、脂肪、维生素和铁、钙、钾等人体所需要的矿物质，蛋白质为优质蛋白，对肝脏组织损伤有修复作用;富含DHA和卵磷脂、卵黄素，对神经系统和身体发育有利，能健脑益智，改善记忆力，并促进肝细胞再生；鸡蛋中含有较多的维生素B和其他微量元素，可以分解和氧化人体内的致癌物质，具有防癌作用。",
        //   peoplenum: "1-2人",
        // },
        // {
        //   title: "红烧鱼",
        //   imgurl: "https://pic.ecook.cn/web/262271769.jpg",
        //   content: "三牙鱼只有一根主刺，蒜瓣肉，肉厚刺少，红烧来吃很过瘾。配着豆腐一起烧，荤素搭配，美味又养生",
        //   peoplenum: "1-2人",
        // },
      ],
    };
  }

  //请求数据
  componentDidMount() {
    //判断是否有网络
    NetInfo.fetch().then(state => {
      //有网络去请求，没网络去本地数据库中取
      if (state.isConnected) {
        banner_data(e => {
          //设置数据
          this.setState({
            entries: e,
          });
        });

      } else {
        //判断是否第一次进入
        storage.get("flag", (err, obj) => {
          //第一次进入
          if (obj == undefined) {
            banner_data(e1 => {
              //设置数据
              this.setState({
                entries: e1,
              });
            });
          } else {
            //没网络 将本地数据，取出来
            storage.get("banner", (err, obj) => {
              // console.log(obj);
              this.setState({
                entries: obj,
              });
            });
          }
        });
      }
    });
  }

  /**
   *   轮播图模板
   */
  _renderItem({ item, index }) {
    // console.log(item, index);
    return (
      <Card cornerRadius={15} style={styles.banner_item}>
        <TouchableNativeFeedback style={{ width: app.w * 0.8 }}
                                 onPress={() => ToastAndroid.show("文本被点击了", ToastAndroid.SHORT)}>
          <View style={{ height: 250 }}>
            {/*轮播图图片*/}
            <Image style={styles.slide} source={{ uri: item.pic }} />
            <View style={styles.card_box1}>
              {/*轮播图标题*/}
              <Text style={styles.card_title}>{item.name}</Text>
            </View>
            <View style={styles.tag}>
              <View style={styles.card_box2}>
                {/*轮播图内容*/}
                <Text escape={false} numberOfLines={2} style={styles.card_content}>{item.content}</Text>
              </View>
            </View>
          </View>
        </TouchableNativeFeedback>
      </Card>
    );
  }

  render() {

    return (
      <View style={styles.box_swiper}>
        {/*轮播图*/}
        <Carousel
          layout={"default"}
          ref={ref => this._carousel = ref}
          data={this.state.entries}
          renderItem={this._renderItem}
          sliderWidth={app.w}
          itemWidth={app.w * 0.8}
          hasParallaxImages={true}
          removeClippedSubviews={false}
          firstItem={1}
          inactiveSlideScale={0.94}
          inactiveSlideOpacity={0.7}
          loop={true}
          loopClonesPerSide={1}
          autoplay={true}
          enableMomentum={true}
          onSnapToItem={(index) => {
            {/*切换时触发*/
            }
          }}
        />
      </View>
    );
  }
}
const styles = StyleSheet.create({

  box_swiper: {
    position: "absolute",
    zIndex: 999,
    marginTop: 150,
    width: "100%",
  },
  slide: {
    borderTopLeftRadius: 10,
    borderTopRightRadius: 10,
    width: "100%",
    height: "73%",
  },
  tag: {
    position: "absolute",
    zIndex: 999,
    width: "100%",
    height: 40,
    bottom: 0,
    borderBottomLeftRadius: 10,
    borderBottomRightRadius: 10,
  },
  banner_item: {
    margin: 10,
    borderRadius: 10,
    width: app.w * 0.8,
  },
  card_box1: {
    width: "100%",
    height: 67,
    backgroundColor: "#fff",
    borderBottomRightRadius: 10,
    borderBottomLeftRadius: 10,
  },
  card_title: {
    marginLeft: 10,
    marginTop: 3,
    fontSize: 16,
    fontWeight: "bold",
    color: "#525657",
  },
  card_box2: {
    flexDirection: "row",
    justifyContent: "space-between",
  },
  card_content: {
    marginLeft: 10,
    marginRight: 10,
    marginBottom: 5,
    fontSize: 12,
    color: "#7A7E81",
  },

});
